package com.example.demo.threadCommunication;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2020年07⽉01⽇<br/>
 * @version：v1.0.0<br>
 */
public class PipedDemo {

    /**
     * 管道输入/输出流和普通的文件输入/输出流或者网络输入/输出流不同之处在于，它主要
     * 用于线程之间的数据传输，而传输的媒介为内存
     * <p>
     * 管道输入/输出流主要包括了如下4种具体实现：PipedOutputStream、PipedInputStream、
     * PipedReader和PipedWriter，前两种面向字节，而后两种面向字符
     * <p>
     * 对于Piped类型的流，必须先要进行绑定，也就是调用connect()方法，如果没有将输入/输
     * 出流绑定起来，对于该流的访问将会抛出异常
     *
     * @param args
     */
    public static void main(String[] args) throws IOException {
        PipedWriter pipedWriter = new PipedWriter();
        PipedReader pipedReader = new PipedReader();
        try {
            pipedWriter.connect(pipedReader);
            Thread printThread = new Thread(new Printer(pipedReader), "PrintThread");
            printThread.start();

            int receive = 0;
            while ((receive = System.in.read()) != -1) {
                pipedWriter.write(receive);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pipedWriter.close();
        }

    }

    static class Printer implements Runnable {

        private PipedReader pipedReader;

        public Printer(PipedReader pipedReader) {
            this.pipedReader = pipedReader;
        }

        @Override
        public void run() {
            int receive = 0;
            try {
                while (((receive = pipedReader.read()) != -1)) {
                    System.out.print((char) receive);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
